import atexit
import queue

import pandas as pd
import requests
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()

from lib import get_fields
from config.settings import CACHE_PATH

class Base:
    cache_base = CACHE_PATH
    def __init__(self, url: str, api_key: str):
        if '/' == url[-1]:
            url = url[:-1]
        self.token = api_key
        self.url = f'{url}/api/v1'
        self.api_header = {
            "Content-Type": "application/json; charset=UTF-8",
            "X-Requested-With": "XMLHttpRequest",
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "RequestValidated": "true",
            "X-Auth": self.token
        }
        self.ScanMode = '11111111-1111-1111-1111-111111111111'
        # 请求初始化
        session = requests.Session()
        self.session = session
        self.session.headers = self.api_header
        self.session.verify = False
        self.targets_id = queue.Queue()
        self.scan_id = queue.Queue()
        self.site = queue.Queue()
        self.__groups = []
        self.awvs = {}

        @atexit.register
        def cleanup():
            session.close()

    def scroll_pages(self, r, api, field, params: str = ''):
        result = r.json()[field]
        cursor = r.json()['pagination']['cursors']

        while len(cursor) > 1:
            c = cursor[1]
            url = f"{api}?{params}&c={c}&l=100"
            r = self.session.get(url)
            result += r.json()[field]
            cursor = r.json()['pagination']['cursors']
        return result

    @staticmethod
    def parse_fields(result, fields):
        export_results = []
        for one in result:
            export_result = {}
            for field in fields:
                value = get_fields(one, field)
                export_result[field] = value
            export_results.append(export_result)
        export_results = pd.DataFrame.from_dict(export_results)
        return export_results

    @property
    def awvs_info(self):
        r = self.session.get(f'{self.url}/me')
        return r.json()

    def __repr__(self):
        return '<AWVS Model>'

